import urllib3
import akshare as ak
import random

# 修正代理池中的格式问题
PROXY_POOL = [
    "http://114.231.41.56:8089",
    "http://114.231.42.248:8089",
    "http://123.182.58.247:8089",
    "http://117.71.149.155:8089",
    "http://114.231.41.106:8089",
    "http://60.5.254.19:8080",
    "http://118.178.232.233:80",
    "http://114.231.45.154:8089",
    "http://114.231.82.41:8089",
    "http://114.232.110.245:8888",
    "http://112.17.16.168:80",
    "http://118.31.112.32:80",
    "http://47.96.252.225:80",
    "http://114.232.110.128:8089",
    "http://42.63.65.31:80",
    "http://221.194.146.141:80",
    "http://120.26.201.73:80",
    "http://183.164.242.67:8089",
    "http://117.71.149.153:8089",
    "http://36.6.145.151:8089",
    "http://36.255.87.133:83",
    "http://36.6.144.60:8089",
    "http://114.232.109.15:8888",
]

def get_random_proxy():
    return random.choice(PROXY_POOL)

# 自定义代理管理器
class ProxyManager:
    def __init__(self):
        self.http = None
        self.update_proxy()

    def update_proxy(self):
        proxy_url = get_random_proxy()
        self.http = urllib3.ProxyManager(proxy_url)
        print(f"更新代理为: {proxy_url}")

    def request(self, method, url, **kwargs):
        try:
            response = self.http.request(method, url, **kwargs)
            if response.status == 200:
                return response.data.decode("utf-8")
            else:
                raise Exception(f"请求失败: {response.status}")
        except Exception as e:
            print(f"代理 {self.http.proxy} 失败，尝试切换: {e}")
            self.update_proxy()  # 失败时切换代理
            return self.request(method, url, **kwargs)  # 重试

    def is_proxy_alive(self, proxy_url):
        try:
            http = urllib3.ProxyManager(proxy_url)
            resp = http.request("GET", "http://httpbin.org/ip")
            return resp.status == 200
        except Exception as e:
            print(e)
            return False

# 替换 AKShare 的默认请求方式
def patch_akshare():
    proxy_manager = ProxyManager()
    ak.session = lambda: proxy_manager.request

    # 测试代理请求
    proxy_url = get_random_proxy()
    print(f"随机选择的代理: {proxy_url}")
    print(f"代理是否存活: {proxy_manager.is_proxy_alive(proxy_url)}")

# 使用示例
if __name__ == "__main__":
    patch_akshare()

    # 测试代理请求
    # data = ak.stock_zh_a_spot()  # 该请求会自动走随机代理
    # print(data.head())
